package com.sgj.juc;

import java.util.concurrent.CountDownLatch;

/**
 * @Author: Guoji Shen
 * @Date: 2021/8/10 9:35
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        // 可以看到，会出现人没走完，班长把门锁了的情况
        // test1();

        // 使用了 CountDownLatch 后，就可以避免这种情况发生
        test2();
    }

    public static void test1() {
        // 6个同学陆续离开教室后，班长锁门
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 号同学离开了教室");
            }, String.valueOf(i)).start();
        }
        System.out.println(Thread.currentThread().getName() + " 班长锁门走人了");
    }

    public static void test2() throws InterruptedException {
        // 创建 CountDownLatch 对象，设置初始值
        CountDownLatch countDownLatch = new CountDownLatch(6);

        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 号同学离开了教室");
                // 计数 -1
                countDownLatch.countDown();
            }, String.valueOf(i)).start();
        }

        // 等待
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + " 班长锁门走人了");

    }
}